﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;

public class NetPacket
{
    public int len = 0;
    public int id = 0;
    public byte[] msg = null;
}

public class MsgMgr
{
    public delegate void MessageHandler(byte[] data);

    static MsgMgr instance = null;
    public static MsgMgr Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new MsgMgr();
            }
            return instance;
        }
    }

    Dictionary<Type, int> msgTypeIdMap = new Dictionary<Type, int>();
    Dictionary<int, Type> msgIdTypeMap = new Dictionary<int, Type>();

    Dictionary<Type, MessageHandler> handlers = new Dictionary<Type, MessageHandler>();


    int id = 0;

    public void Register<T>()
    {
        msgTypeIdMap[typeof(T)] = id;
        msgIdTypeMap[id] = typeof(T);

        ++id;
    }
    public int GetId<T>()
    {
        return msgTypeIdMap[typeof(T)];
    }
    public Type GetType(int id)
    {
        return msgIdTypeMap[id];
    }

    public byte[] GetBytes(ushort value)
    {
        byte[] msgId = BitConverter.GetBytes((ushort)(value));
        if (BitConverter.IsLittleEndian) // 若为 小端模式
        {
            Array.Reverse(msgId); // 转换为 大端模式               
        }

        return msgId;
    }

    public NetPacket GetNetPacket(byte[] bytes)
    {
        byte[] lenBytes = new byte[2];
        Array.Copy(bytes, 0, lenBytes, 0, 2);
        if (BitConverter.IsLittleEndian) // 若为 小端模式
        {
            Array.Reverse(lenBytes); // 转换为 大端模式               
        }


        byte[] idBytes = new byte[2];
        Array.Copy(bytes, 2, idBytes, 0, 2);
        if (BitConverter.IsLittleEndian) // 若为 小端模式
        {
            Array.Reverse(idBytes); // 转换为 大端模式               
        }

        return new NetPacket()
        {
            len = BitConverter.ToInt16(lenBytes, 0),
            id = BitConverter.ToInt16(idBytes, 0),
            msg = bytes.Skip(4).Take(bytes.Length - 4).ToArray(),
        };
    }


    public void SetMessageHandler<T>(MessageHandler handler)
    {
        handlers[typeof(T)] = handler;
    }
    public MessageHandler GetMessageHandler(Type type)
    {
        return handlers[type];
    }

    //public T Deserialize<T>(byte[] data)
    //{
    //    T msg = new T();
    //    msg.MergeFrom(data);
    //    return msg;
    //}

    public void Init()
    {
        Register<MsgHello>();
        Register<ClientLogin>();
        Register<ServerLogin>();
        Register<ClientFullRows>();
        Register<ServerFullRows>();
    }
}
